home *** CD-ROM | disk | FTP | other *** search
- Path: erich.triumf.ca!bennett
- From: bennett@erich.triumf.ca (P.Bennett)
- Newsgroups: comp.lang.c
- Subject: Re: Returning string from function (how?)
- Date: 30 Mar 1996 09:28 PST
- Organization: TRIUMF: Tri-University Meson Facility
- Distribution: world
- Message-ID: <30MAR199609281747@erich.triumf.ca>
- References: <4jj4hh$m9n@news.xs4all.nl>
- NNTP-Posting-Host: erich.triumf.ca
- News-Software: VAX/VMS VNEWS 1.50
-
- In article <4jj4hh$m9n@news.xs4all.nl>, jordan@xs4all.nl (Jordan) writes...
- >Hi all, i'm trying to get a string returned from a function, but it's not
- >working as i planed.
-
- >char s;
-
- this reserves space for exactly one char. If you want to declare space to
- store a string, you need something like:
- char str[80]; /* allow space for the largest string you expect */
- /* and have the input routine limit input to this */
- /* size */
-
- >char get_str(void)
- >{
- > int i;
- > char ch, string;
- /* this should also be char string[80]; (or big enough...) */
- >
- > i=0;
- > printf("Enter a string: ");
- > while((ch = getchar()) != '\n' && i < MAX)
- > string[i++] = ch;
- > string[i] = '\0';
- >
- > return string;
-
- This returns (or would, if you had char string[80];) a pointer to an automatic
- variable, which will vanish when the function returns. If you declare:
- static char string[80];
- this would work.
-
- I deleted a line "s = get_str();" above. that should be replaced with:
- strcpy(s, get_str());
- In C, you can't copy strings with an "=".
-
- Perhaps a better technique would be to have the caller pass the string (and a
- size limit) to get_str() - have a look at fgets().
-
- Peter Bennett VE7CEI | Vessels shall be deemed to be in sight
- Internet: bennett@triumf.ca | of one another only when one can be
- Packet: ve7cei@ve7kit.#vanc.bc.ca | observed visually from the other
- TRIUMF, Vancouver, B.C., Canada | ColRegs 3(k)
- GPS and NMEA info and programs: ftp://sundae.triumf.ca/pub/peter/index.html
- or: ftp://ftp-i2.informatik.rwth-aachen.de/pub/arnd/GPS/peter/index.html
-
-
-
-
-
-
-